/**
 * MongoDB 数据库配置
 * 使用硬编码配置，符合项目风格
 */

import mongoose from 'mongoose';

// 硬编码的MongoDB配置
const MONGODB_CONFIG = {
  URI: 'mongodb+srv://1191665779:20020219aa@zn.apmsejq.mongodb.net/medical_digital_twin',
  DB_NAME: 'medical_digital_twin',
  OPTIONS: {
    // 移除已废弃的选项：useNewUrlParser 和 useUnifiedTopology
    maxPoolSize: 10,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
    family: 4,
    retryWrites: true,
    w: 'majority' as const
  }
};

// 数据库连接状态
let isConnected = false;

/**
 * 连接MongoDB数据库
 */
export async function connectMongoDB(): Promise<typeof mongoose> {
  try {
    if (isConnected) {
      console.log('[MongoDB] 数据库已连接');
      return mongoose;
    }

    console.log('[MongoDB] 正在连接数据库...');
    const connection = await mongoose.connect(MONGODB_CONFIG.URI, MONGODB_CONFIG.OPTIONS);
    
    isConnected = true;
    console.log('[MongoDB] ✅ 数据库连接成功');
    
    // 监听连接事件
    mongoose.connection.on('connected', () => {
      console.log('[MongoDB] 📡 连接已建立');
    });

    mongoose.connection.on('error', (error) => {
      console.error('[MongoDB] ❌ 连接错误:', error);
      isConnected = false;
    });

    mongoose.connection.on('disconnected', () => {
      console.log('[MongoDB] ⚠️ 连接已断开');
      isConnected = false;
    });

    return connection;
  } catch (error) {
    console.error('[MongoDB] ❌ 连接失败:', error);
    isConnected = false;
    throw error;
  }
}

/**
 * 断开数据库连接
 */
export async function disconnectMongoDB(): Promise<void> {
  try {
    if (!isConnected) {
      console.log('[MongoDB] 数据库未连接');
      return;
    }

    await mongoose.connection.close();
    isConnected = false;
    console.log('[MongoDB] ✅ 数据库连接已关闭');
  } catch (error) {
    console.error('[MongoDB] ❌ 关闭连接失败:', error);
    throw error;
  }
}

/**
 * 获取连接状态
 */
export function getConnectionStatus() {
  return {
    isConnected,
    readyState: mongoose.connection.readyState,
    host: mongoose.connection.host,
    port: mongoose.connection.port,
    name: mongoose.connection.name
  };
}

/**
 * 检查数据库连接
 */
export async function checkConnection(): Promise<boolean> {
  try {
    if (!isConnected) {
      return false;
    }

    await mongoose.connection.db?.admin().ping();
    return true;
  } catch (error) {
    console.error('[MongoDB] 连接检查失败:', error);
    isConnected = false;
    return false;
  }
}

// 导出配置常量
export { MONGODB_CONFIG };